//
//  UIView+border.m
//  JigSaw
//
//  Created by Slim Wang on 15/4/2.
//  Copyright (c) 2015年 LITB. All rights reserved.
//

#import "UIView+border.h"
#import "UIColor+Help.h"

@implementation UIView (border)

@dynamic borderLayer;

- (void)addBorder
{
    for (CALayer* subLayer in self.layer.sublayers) {
        if ([subLayer.name isEqualToString:@"borderLayer"]) {
            [subLayer removeFromSuperlayer];
        }
    }
    CAShapeLayer* borderLayer = [CAShapeLayer layer];
    borderLayer.name = @"borderLayer";
    CGMutablePathRef path = CGPathCreateMutable();
    CGRect frame = self.bounds;
//    CGFloat cornerRadius = 0;
    CGFloat margin = 2.0;
    //drawing a border around a view
    CGPathMoveToPoint(path, NULL, 0 - margin, frame.size.height + margin);
    CGPathAddLineToPoint(path, NULL, 0 - margin, 0 - margin);
//    CGPathAddArc(path, NULL, cornerRadius, cornerRadius, cornerRadius, M_PI, -M_PI_2, NO);
    CGPathAddLineToPoint(path, NULL, frame.size.width + margin, 0 - margin);
//    CGPathAddArc(path, NULL, frame.size.width - cornerRadius, cornerRadius, cornerRadius, -M_PI_2, 0, NO);
    CGPathAddLineToPoint(path, NULL, frame.size.width + margin, frame.size.height + margin);
//    CGPathAddArc(path, NULL, frame.size.width - cornerRadius, frame.size.height - cornerRadius, cornerRadius, 0, M_PI_2, NO);
    CGPathAddLineToPoint(path, NULL, 0 - margin, frame.size.height + margin);
//    CGPathAddArc(path, NULL, cornerRadius, frame.size.height - cornerRadius, cornerRadius, M_PI_2, M_PI, NO);
    
    //path is set as the layer object's path
    borderLayer.path = path;
    CGPathRelease(path);
    borderLayer.backgroundColor = [[UIColor clearColor] CGColor];
    borderLayer.frame = frame;
    borderLayer.masksToBounds = NO;
    [borderLayer setValue:[NSNumber numberWithBool:NO] forKey:@"isCircle"];
    borderLayer.fillColor = [[UIColor clearColor] CGColor];
    borderLayer.strokeColor = [[UIColor colorWithHex:0xffe049] CGColor];
    borderLayer.lineWidth = 1.5;
    borderLayer.lineCap = kCALineCapRound;
    [self.layer addSublayer:borderLayer];
    self.layer.masksToBounds = NO;
}
- (void)removeBorder
{
    CALayer* borderLayer = NULL;
    for (CALayer* subLayer in self.layer.sublayers) {
        if ([subLayer.name isEqualToString:@"borderLayer"]) {
            borderLayer = subLayer;
        }
    }
    [borderLayer removeFromSuperlayer];
}

- (void)showBorder
{
    for (CALayer* subLayer in self.layer.sublayers) {
        if ([subLayer.name isEqualToString:@"borderLayer"]) {
            subLayer.opaque = NO;
        }
    }
}

- (void)hideBorder
{
    for (CALayer* subLayer in self.layer.sublayers) {
        if ([subLayer.name isEqualToString:@"borderLayer"]) {
            subLayer.opaque = YES;
        }
    }
}
@end
